// https://leetcode.cn/problems/add-to-array-form-of-integer/
// Created by ade on 2022/8/23.
//
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    // 原地修改，但是insert好像会影响性能
    vector<int> addToArrayForm1(vector<int> &num, int k) {
        int len = num.size();
        int i = len - 1;
        int add = 0;
        while (k > 0 || add == 1) {
            int res = 0;
            if (i < 0) {
                res = k % 10 + add;
            } else {
                res = num[i] + k % 10 + add;
            }
            if (res >= 10) {
                add = 1;
            } else {
                add = 0;
            }
            if (i < 0) {
                num.insert(num.begin(), res % 10);
            } else {
                num[i] = res % 10;
            }
            k = (k - k % 10) / 10;
            i--;
        }

        return num;
    }

    vector<int> addToArrayForm(vector<int> &num, int k) {
        reverse(num.begin(), num.end());
        vector<int> result = {};
        int add = 0;
        int i = 0;
        int len = num.size();
        while (k > 0 || add == 1 || i < len) {
            int res = 0;
            if (i >= len) {
                res = k % 10 + add;
            } else {
                res = k % 10 + num[i] + add;
            }

            if (res >= 10) {
                res -= 10;
                add = 1;
            } else {
                add = 0;
            }
            result.push_back(res);
            k = (k - k % 10) / 10;
            i++;
        }
        reverse(result.begin(), result.end());
        return result;
    }
};

int main() {
    Solution so;
    vector<int> nums = {0};
    auto a = so.addToArrayForm(nums, 806);
    for (auto i : a) {
        cout << i << ",";
    }
    return 0;
}